<template>
  <div class="users-container">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="addDialogVisible=true"
          >添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table
        :data="userlist"
        border
        stripe
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
        >
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
        >
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
        >
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
        >
        </el-table-column>
        <!-- 状态区域 -->
        <el-table-column label="状态">
          <!-- 核心作用点 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>

        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              v-model="scope.row.username"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              v-model="scope.row.username"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>

            <el-tooltip
              effect="dark"
              content="角色分配"
              placement="top-start"
              :enterable="false"
            >
              <!-- 角色分配按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                v-model="scope.row.username"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->

      <el-form
        :model="addFrom"
        :rules="addFromRules"
        ref="addFromRef"
        label-width="70px"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input v-model="addFrom.username"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input v-model="addFrom.password"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="addFrom.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机"
          prop="mobile"
        >
          <el-input v-model="addFrom.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUser"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50"
      @close="editDialogClosed"
    >
      <el-form
        :model="editFrom"
        :rules="editFromRules"
        ref="editFromRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="editFrom.username"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="editFrom.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机"
          prop="mobile"
        >
          <el-input v-model="editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible= false">取 消</el-button>
        <el-button
          type="primary"
          @click="editUserInfo"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50"
    >
      <p>当前的用户：{{userinfo.username}}</p>
      <P>当前的角色：{{userinfo.role_name}}</P>
      <p>分配新的角色：
        <el-select
          v-model="selectedRoleId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in roleslist"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRoleDialogVisible= false">取 消</el-button>
        <el-button
          type="primary"
          @click="saveRoleInfo"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      // console.log(rule)
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+/
      // 通过 regEmail.test(） 就能验证指定的值是否合法
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error("请输入合法的邮箱"))
    }
    const checkMobile = (rule, value, cb) => {
      // console.log(rule)
      const regMobile =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error("请输入合法手机号"))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      // 所有的用户列表
      userlist: [],
      // 总数与条数
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addFrom: {},
      //  添加表单的验证规则对象
      addFromRules: {
        username: [
          { required: true, message: "请输入用户名", tirgger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在3到10个字符之间",
            tirgger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", tirgger: "blur" },
          {
            min: 6,
            max: 10,
            message: "密码的长度在6到15个字符之间",
            tirgger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", tirgger: "blur" },
          { validator: checkEmail, tirgger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号码", tirgger: "blur" },
          { validator: checkMobile, tirgger: "blur" }
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editFrom: {},
      // 编辑查询到的表单的验证规则对象
      editFromRules: {
        email: [
          { required: true, message: "请输入邮箱", tirgger: "blur" },
          { validator: checkEmail, tirgger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号码", tirgger: "blur" },
          { validator: checkMobile, tirgger: "blur" }
        ]
      },
      // 需要被分配的角色用户信息
      userinfo: {},
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 所有的角色数据列表
      roleslist: [],
      // 已选中的角色id
      selectedRoleId: ""
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.Message.error("获取用户列表失败")
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 监听pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听swtich
    async userStateChange(userinfo) {
      console.log(userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$Message.error("更改用户状态失败")
      }

      this.$Message.success("更改用户状态成功")
    },
    // 添加用户对话框重置功能
    addDialogClosed() {
      this.$refs.addFromRef.resetFields()
    },
    addUser() {
      this.$refs.addFromRef.validate(async valid => {
        if (!valid) return
        // 可以发起用户请求
        const { data: res } = await this.$http.post("users", this.addFrom)
        if (res.meta.status !== 201) {
          this.$Message.error("添加用户失败")
        }
        this.$Message.success("添加用户成功")
        // 隐藏用户的对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("users/" + id)
      if (res.meta.status !== 200) {
        return this.$Message.error("查询用户信息失败")
      }
      this.editFrom = res.data
      // 显示修改用户对话框
      this.editDialogVisible = true
      console.log(this.editFrom)
    },
    // 监听修改用户框的关闭事件
    editDialogClosed() {
      this.$refs.editFromRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFromRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put(
          "users/" + this.editFrom.id,
          {
            email: this.editFrom.email,
            mobile: this.editFrom.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$Message.error("更新用户信息失败")
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$Message.success("更新用户信息成功")
      })
    },
    // 根据id删除对应的信息
    async removeUserById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err)
      // 如果用户确认删除则返回值为字符串 confirm
      // 如果用户取消删除这返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== "confirm") {
        return this.$Message.info("已经取消删除")
      }
      console.log("确认删除")
      const { data: res } = await this.$http.delete("users/" + id)
      if (res.meta.status !== 200) {
        return this.$Message.error("删除失败")
      }
      this.$Message.success("删除成功")
      // 删除之后刷新数据列表
      this.getUserList()
    },
    // 控制分配角色对话框的显示与隐藏，并获取角色数据
    async setRole(userinfo) {
      // 先把当前要被展示的用户信息存到data中
      this.userinfo = userinfo
      // 在展示对话框之前获取所有的角色列表
      const { data: res } = await this.$http.get("roles")
      if (res.meta.status !== 200) {
        return this.$Message.error("获取角色数据失败")
      }
      this.roleslist = res.data
      console.log(this.roleslist)
      this.setRoleDialogVisible = true
    },
    // 点击按钮 分配角色
    async saveRoleInfo(id) {
      if (!this.selectedRoleId) {
        return this.$Message.error("请选择要分配的角色")
      }
      const { data: res } = await this.$http.put(`users/${this.userinfo.id}/`, {
        rid: this.selectedRoleId
      })
      if (res.meta.status !== 200) {
        return this.$Message.error("分配角色失败")
      }
      this.$Message.success("更新角色成功")
      // 重新获取用户信息
      this.getUserList()
      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
